package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"shopping/pkg"
	"time"

	"shopping/api/internal/svc"
	"shopping/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductUploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProductUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductUploadLogic {
	return &ProductUploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ProductUploadLogic) ProductUpload(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line

	file, m, err := req.FormFile("img")
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    "500",
			Data:    nil,
		}, nil
	}
	if m.Size > 2*1024*1024 {
		return &types.Response{
			Message: "图片尺寸大小不能超过2M",
			Code:    "500",
			Data:    nil,
		}, nil
	}
	ext := filepath.Ext(m.Filename)

	if ext != ".jpg" {
		return &types.Response{
			Message: "图片类型格式必须是.jpg",
			Code:    "500",
			Data:    nil,
		}, nil
	}
	name := time.Now().Format("20060102150405") + ext

	upload, err := pkg.Upload(file, name)
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    "500",
			Data:    nil,
		}, nil
	}

	return &types.Response{
		Message: "上传成功",
		Code:    "200",
		Data:    upload,
	}, nil
}
